import indexDb from './indexDb.js';
import WebWorker from './webWorker.js';

const loadScript = (url) => {
    if (!url) {
        return;
    }
    return new Promise((resolve) => {
        const script = document.createElement("script");
        script.type = "text/javascript";
        script.src = url;
        script.onload = (e) => {
            resolve();
        }
        document.body.appendChild(script);
    });
}

(async () => {
    /* indexDB */
    /**
        const db = new indexDb("index", 22);
        await db.createDatabase([{tableName: "table_1", keyPath: "table_1_id"}, {tableName: "table_2", keyPath: "table_2_id"}, {tableName: "table_3"}]);
        console.log(db.getTables());
        
        await db.addData("table_1", {table_1_id: 1, f_1: 1, f_2: 1});
        await db.addData("table_1", {table_1_id: 2, f_1: 2, f_2: 2});
        console.log(await db.getDataById("table_1", 2));
        console.log(await db.getAllData("table_1"));
        await db.update("table_1", {table_1_id: 2,f_1: "changed", f_2: "changed"});
        console.log(await db.getAllData("table_1"));
        await db.deleteData("table_1", 2);
        console.log(await db.getAllData("table_1"));


        await db.addData("table_2", {f_1: 1, f_2: 1});
        await db.addData("table_2", {f_1: 2, f_2: 2});
        console.log(await db.getDataById("table_2", 2));
        console.log(await db.getAllData("table_2"));
        await db.update("table_2", {table_2_id: 2,f_1: "changed", f_2: "changed"});
        console.log(await db.getAllData("table_2"));
        await db.deleteData("table_2", 2);
        console.log(await db.getAllData("table_2"));


        await db.addData("table_3", {f_1: 1, f_2: 1});
        await db.addData("table_3", {f_1: 2, f_2: 2});
        console.log(await db.getDataById("table_3", 2));
        console.log(await db.getAllData("table_3"));
        await db.update("table_3", {id: 2,f_1: "changed", f_2: "changed"});
        console.log(await db.getAllData("table_3"));
        await db.deleteData("table_3", 2);
        console.log(await db.getAllData("table_3"));
     */

    /* webWorker */
    /**
        let i = 0;

        document.getElementById("root").addEventListener("click", () => {
            i++;
            document.getElementById("root").innerText = i;
        });

        const worker = new WebWorker({
            filePath: "./worker.js",
            action: (args) => {
                console.log("计算结果：", args);
            }
        });
        worker.createWorker();
        worker.postMessage({action: "importScripts", args: {scriptPath: "./worker_calc.js"}});
        worker.postMessage({action: "startWorker", args: {length: 9999}});
     */

    /* 文件处理 */

    await loadScript("./spark-md5.min.js");
    let md5Arr = [];
    const spark_1 = new SparkMD5.ArrayBuffer();

    const fileMd5 = (file) => {
        const spark_2 = new SparkMD5.ArrayBuffer();
        spark_1.append(file);
        spark_2.append(file);
        const hexHash = spark_2.end();
        md5Arr.push(hexHash);
    }

    const readFile = (file) => {
        return new Promise((resolve) => {
            const reader = new FileReader();
            reader.readAsArrayBuffer(file);
            reader.addEventListener('loadstart', (event) => {
                console.log("开始读取。。。");
            });
            reader.addEventListener('error', (event) => {
                console.log("读取出错。。。");
                console.error(event);
                resolve(false);
            });
            reader.addEventListener('loadend', (event) => {
                console.log("读取完成。。。1");
            });
            reader.addEventListener('load', () => {
                //console.log(reader.result);
                console.log("读取完成。。。2");
                resolve(reader.result);
            });
        });
    }

    const option = { hash: 'hash', blob: 'blob', chunkSize: 2 * 1024 * 1024 };

    const chunkSlice = async (fileSource) => {
        let index = 0;
        for (let i = 0; i < fileSource.size; i += option.chunkSize) {
            const fileChunk = await readFile(fileSource.slice(i, i + option.chunkSize));
            if (fileChunk) {
                fileMd5(fileChunk);
            }
            index++;
            document.getElementById("percentage").innerText = `${parseInt((index * option.chunkSize) / fileSource.size * 100)}%`;
        }
        const hexHash = spark_1.end();
        document.getElementById("md5").innerText = hexHash;
        console.log(md5Arr);
    }

    const fileInput = document.getElementById('inputId');
    fileInput.addEventListener('change', async (event) => {
        const file = event.target.files[0];
        if (file) {
            document.getElementById("fileName").innerText = file.name;
            document.getElementById("fileSize").innerText = `${Math.floor(file.size / 1024 / 1024 / 1024 * 100) / 100} G`;
            document.getElementById("md5").innerText = "计算中。。。";

            /* 7447c6e6be379ca69237d8d610778f49 */

            await chunkSlice(file);
        }
    });
})();